/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.infrastructure.plugin.captcha;

import cn.hallele.infrastructure.data.client.CacheClient;
import cn.hallele.infrastructure.metadata.constant.HttpConst;
import cn.hallele.infrastructure.util.NetUtil;
import cn.hallele.infrastructure.util.ObjectUtil;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/10/11 23:03
 */
public class CaptchaClient {
    /**
     * 图片宽
     */
    private int width = 120;

    /**
     * 图片高
     */
    private int height = 40;

    /**
     * 字符个数
     */
    private int codeCount = 4;

    /**
     * 验证码干扰元素个数
     */
    private int interfereCount = 3;

    /**
     * 验证码过期时间，单位：s，默认60s
     */
    private long ttl = 60;

    /**
     * 构造函数
     *
     * @param codeCount      codeCount
     * @param height         height
     * @param interfereCount interfereCount
     * @param ttl            ttl
     * @param width          width
     */
    public CaptchaClient(int codeCount, int height, int interfereCount, long ttl, int width) {
        this.codeCount = codeCount;
        this.height = height;
        this.interfereCount = interfereCount;
        this.ttl = ttl;
        this.width = width;
    }

    /**
     * 验证码对象
     *
     * @return 验证码对象
     */
    public PortalCaptcha getPortalCaptcha() {
        return new PortalCaptcha(width,
                height,
                codeCount,
                interfereCount,
                ttl);
    }

    /**
     * 验证验证码是否正确，建议忽略大小写
     *
     * @param userInput 用户输入的验证码
     * @return 是否与生成的一直, true为一致
     */
    public boolean verify(String userInput) {
        String captchaCode = CacheClient.getAndDelete(HttpConst.CAPTCHA_KEY_PREFIX +
                NetUtil.getHttpServletRequest().getParameter(HttpConst.CAPTCHA_KEY));
        return ObjectUtil.equalsIgnoreCase(userInput, captchaCode);
    }
}
